package com.l.shirodemo.controller;

import com.l.shirodemo.pojo.Login;
import com.l.shirodemo.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {
    @Autowired
    private LoginService loginService;

    @RequestMapping("/login")
    public String login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {

            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                token.setRememberMe(true);
                subject.login(token);
                return "redirect:index.jsp";
            } catch (AuthenticationException e) {
                System.out.println("登录失败");
                e.printStackTrace();
            }
        }
        return "error";
    }

    @RequiresRoles(value = {"admin","user"},logical = Logical.OR)
    @RequestMapping("/toSuccess")
    public String success(String username, String password) {

        return "success";
    }

    @RequiresRoles({"admin"})
    @RequestMapping("/reg")
    public String reg(Login login){
//        次数使用的方法和shiro验证时的方法一致，所有需要 加密算法 和加密次数 与 realm中 credentialsMatcher 属性中配置的算法和次数相同（在配置文件spring_shiro.xml中的配置）
        SimpleHash md5 = new SimpleHash("md5", login.getPassword(), login.getUsername(), 32);
        System.out.println(md5);
        login.setPassword(md5.toString());
        if (loginService.add(login)==1){
            return "success";
        }
        return "error";
    }

}
